package com.jp.knowledge.view;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ProgressBar;

import com.google.gson.JsonObject;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.dialog.CommDialog;
import com.jp.knowledge.util.JsonUtil;
import com.jp.knowledge.util.L;
import com.jp.knowledge.webUtil.JavaScriptInterface;
import com.jp.knowledge.webUtil.X5WebView;
import com.tencent.smtt.export.external.interfaces.JsResult;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.export.external.interfaces.WebResourceResponse;
import com.tencent.smtt.sdk.CookieSyncManager;
import com.tencent.smtt.sdk.DownloadListener;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.tencent.smtt.utils.TbsLog;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Created by 528787067@qq.com on 2017/2/10.
 */

public class JpWebView extends FrameLayout implements View.OnClickListener {

    protected Context context;
    protected View contentView;
    protected X5WebView webView;
    protected WebViewClient webViewClient;
    protected WebChromeClient webChromeClient;
    protected DownloadListener downloadListener;
    private ProgressBar progressBar;
    private View loadingView;
    private View reloadView;

    private boolean isClearBeforeLoading;
    private boolean isShowProgressBar;
    private boolean isShowLoadingAnimation;
    private boolean isShowReloadViewOnFail;

    private Handler handler;
    private CommDialog downloadDialog;

    public JpWebView(Context context) {
        super(context);
        init(context);
    }

    public JpWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public JpWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    protected void init(Context context){
        this.isClearBeforeLoading = false;
        this.isShowProgressBar = false;
        this.isShowLoadingAnimation = true;
        this.isShowReloadViewOnFail = true;

        this.context = context;
        this.contentView = View.inflate(context, R.layout.jp_webveiew_layout, null);
        this.webView = (X5WebView) contentView.findViewById(R.id.webView);
        this.progressBar = (ProgressBar) contentView.findViewById(R.id.progressBar);
        this.loadingView = contentView.findViewById(R.id.gifImageView);
        this.reloadView = contentView.findViewById(R.id.reload);

        downloadDialog = new CommDialog(context);
        downloadDialog.setContent("是否下载该文件？");
        downloadDialog.setLeft("取消");
        downloadDialog.setRight("确定");
        downloadDialog.setRightListener(this);
        reloadView.setOnClickListener(this);

        initHandler();
        initWebView();
        this.addView(contentView);
    }

    private void initHandler(){
        handler = new Handler() {
            public void handleMessage(Message msg) {
                JsonObject obj = JsonUtil.getInstance().strToJson(msg.obj.toString());
                if (jsCallbackListener != null)
                    jsCallbackListener.onJsCallback(obj);
            }
        };
    }

    protected void initWebView(){
        webViewClient = new WebViewClient(){
            @Override
            public void onPageStarted(WebView webView, String s, Bitmap bitmap) {
                JpWebView.this.onPageStarted(webView, s, bitmap);
            }
            @Override
            public void onPageFinished(WebView webView, String s) {
                JpWebView.this.onPageFinished(webView, s);
            }
            @Override
            public void onReceivedError(WebView webView, int i, String s, String s1) {
                JpWebView.this.onReceivedError(webView, i, s, s1);
            }
            @Override
            public void onReceivedHttpError(WebView webView, WebResourceRequest webResourceRequest, WebResourceResponse webResourceResponse) {
                JpWebView.this.onReceivedHttpError(webView, webResourceRequest, webResourceResponse);
            }
        };
        webChromeClient = new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                JpWebView.this.onReceivedTitle(view, title);
            }
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                JpWebView.this.onProgressChanged(view, newProgress);
            }
            @Override
            public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
                return JpWebView.this.onJsAlert(view, url, message, result);
            }
        };
        downloadListener = new DownloadListener() {
            @Override
            public void onDownloadStart(String arg0, String arg1, String arg2, String arg3, long arg4) {
                downloadDialog.setTag(arg0);
                downloadDialog.show();
            }
        };
        webView.setWebViewClient(webViewClient);
        webView.setWebChromeClient(webChromeClient);
        webView.setDownloadListener(downloadListener);

        WebSettings webSetting = webView.getSettings();
        webSetting.setAllowFileAccess(true);
        webSetting.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
//        webSetting.setSupportZoom(true);
//        webSetting.setBuiltInZoomControls(false);
//        webSetting.setUseWideViewPort(true);
        webSetting.setSupportMultipleWindows(false);
        webSetting.setLoadWithOverviewMode(true);
        webSetting.setAppCacheEnabled(true);
        webSetting.setDatabaseEnabled(true);
        webSetting.setDomStorageEnabled(true);
        webSetting.setJavaScriptEnabled(true);
        webSetting.setGeolocationEnabled(true);
        webSetting.setAppCacheMaxSize(Long.MAX_VALUE);
        webSetting.setAppCachePath(context.getDir("appcache", 0).getPath());
        webSetting.setDatabasePath(context.getDir("databases", 0).getPath());
        webSetting.setGeolocationDatabasePath(context.getDir("geolocation", 0).getPath());
        webSetting.setPluginState(WebSettings.PluginState.ON_DEMAND);
        webSetting.setRenderPriority(WebSettings.RenderPriority.HIGH);
        long time = System.currentTimeMillis();
        TbsLog.d("time-cost", "cost time: " + (System.currentTimeMillis() - time));
        CookieSyncManager.createInstance(context);
        CookieSyncManager.getInstance().sync();
//        webView.getSettings().setUserAgentString("app_jp;jp580.com");
        webView.addJavascriptInterface(new JavaScriptInterface(handler), "Android");
        X5WebView.setSmallWebViewEnabled(true);
    }

    /* 网页加载开始回调 */
    protected void onPageStarted(WebView webView, String s, Bitmap bitmap) {
        if(isClearBeforeLoading)
            webView.clearView();
        if(isShowProgressBar){
            progressBar.setProgress(0);
            progressBar.setVisibility(VISIBLE);
        }
        if(isShowLoadingAnimation)
            loadingView.setVisibility(VISIBLE);
        if(webViewCallback != null)
            webViewCallback.onPageStarted(webView, s, bitmap);
    }

    /* 网页加载完成回调 */
    protected void onPageFinished(WebView webView, String s) {
        progressBar.setVisibility(GONE);
        loadingView.setVisibility(GONE);
        if(webViewCallback != null)
            webViewCallback.onPageFinished(webView, s);
    }

    /* 网页加载出错回调 */
    protected void onReceivedError(WebView webView, int i, String s, String s1) {
        if(isShowReloadViewOnFail){
            webView.clearView();
            reloadView.setVisibility(GONE);
        }
        if(webViewCallback != null)
            webViewCallback.onReceivedError(webView, i, s , s1);
    }

    /* 网页加载出现 http 错误回调 */
    protected void onReceivedHttpError(WebView webView, WebResourceRequest webResourceRequest, WebResourceResponse webResourceResponse) {
        if(webViewCallback != null)
            webViewCallback.onReceivedHttpError(webView, webResourceRequest, webResourceResponse);
    }

    /* 加载完网页标题回调 */
    protected void onReceivedTitle(WebView view, String title){
        if(webViewCallback != null)
            webViewCallback.onReceivedTitle(view, title);
    }

    /* 网页加载进度回调 */
    protected void onProgressChanged(WebView view, int newProgress) {
        if(isShowProgressBar)
            progressBar.setProgress(newProgress);
    }

    /* 处理 JS 对话框回调 */
    protected boolean onJsAlert(WebView view, String url, final String message, final JsResult result){
        return false;
    }

    public boolean loadUrl(String url){
        if(url == null)
            return false;
        webView.loadUrl(url);
        return true;
    }

    public boolean loadHtml(String html){
        if(html == null)
            return false;
        webView.loadDataWithBaseURL("about:blank", html, "text/html", "utf-8", null);
        return true;
    }

    public void reload(){
        webView.reload();
    }

    public void loadJavaScript(String javaScript){
        if(javaScript == null)
            return;
        if(javaScript.startsWith("javascript:"))
            webView.loadUrl(javaScript);
        else
            webView.loadUrl("javascript:" + javaScript);
    }

    public boolean goBack(){
        if(webView.canGoBack()) {
            webView.goBack();
            return true;
        }
        return false;
    }

    public void cancelLoading(){
        webView.stopLoading();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.reload:
                reload();
                break;
            case R.id.right_btn:
                context.startActivity(new Intent(Intent.ACTION_VIEW,
                        Uri.parse((String) downloadDialog.getTag())));
                ToasUtil.toast(context, "开始下载文件...");
                downloadDialog.cancel();
                break;
        }
    }

    /* 读取 html 模板 */
    protected String getHtmlTemple(String fileName){
        String htmlTemple = "";
        try {
            InputStream inputStream = getResources().getAssets().open(fileName);
            InputStreamReader inputReader = new InputStreamReader(inputStream);
            BufferedReader bufReader = new BufferedReader(inputReader);
            String line="";
            while((line = bufReader.readLine()) != null)
                htmlTemple += line;
            bufReader.close();
            inputReader.close();
            inputStream.close();
        } catch (Exception e) {
            L.e(e.toString());
        }
        return htmlTemple;
    }

    public void setClearBeforeLoading(boolean clearBeforeLoading) {
        isClearBeforeLoading = clearBeforeLoading;
    }

    public void setShowProgressBar(boolean showProgressBar) {
        isShowProgressBar = showProgressBar;
        if (!isShowProgressBar)
            progressBar.setVisibility(GONE);
    }

    public void setShowLoadingAnimation(boolean showLoadingAnimation) {
        isShowLoadingAnimation = showLoadingAnimation;
        if (!showLoadingAnimation)
            loadingView.setVisibility(GONE);
    }

    public void setShowReloadViewOnFail(boolean showReloadViewOnFail) {
        isShowReloadViewOnFail = showReloadViewOnFail;
        if(!isShowReloadViewOnFail)
            reloadView.setVisibility(GONE);
    }

    public void destory(){
        webView.destroy();
    }

    public X5WebView getWebView(){
        return webView;
    }
    public WebSettings getWebSettings(){
        return webView.getSettings();
    }
    public View getLoadingAnimationView(){
        return loadingView;
    }
    public String getUrl(){
        return webView.getUrl();
    }

    protected WebViewCallback webViewCallback;
    public void setWebViewCallback(WebViewCallback webViewCallback){
        this.webViewCallback = webViewCallback;
    }
    public interface WebViewCallback {
        void onPageStarted(WebView webView, String s, Bitmap bitmap);
        void onPageFinished(WebView webView, String s);
        void onReceivedError(WebView webView, int i, String s, String s1);
        void onReceivedHttpError(WebView webView, WebResourceRequest webResourceRequest, WebResourceResponse webResourceResponse);
        void onReceivedTitle(WebView view, String title);
        void onProgressChanged(WebView view, int newProgress);
    }

    private JsCallbackListener jsCallbackListener;
    public void setJsCallbackListener(JsCallbackListener jsCallbackListener){
        this.jsCallbackListener = jsCallbackListener;
    }
    public interface JsCallbackListener{
        void onJsCallback(JsonObject obj);
    }
}
